package edu.sjb.threads;

import java.awt.Rectangle;
import java.util.ArrayList;

import edu.sjb.map.GameEntity;
import edu.sjb.map.MapObject;

public class GravityThread implements Runnable {
	protected GameEntity underEffect;

	public GravityThread(GameEntity ge) {
		underEffect = ge;
	}

	public void run() {
		if (underEffect.game().isMarioDead()) {
			while (underEffect.posY() < 645) {
				fall(3);
			}
			underEffect.game().finishGame();
		}
		else {
			while (onAir()) {
				fall(15);
			}
		}
	}

	private void fall(int spd) {
		underEffect.setPosY(underEffect.posY() + 1);
		try {
			Thread.sleep(spd);
		}
		catch (InterruptedException e) {
		}
	}

	public boolean onAir() {
		int floorLevel = 512;
		if (underEffect.sizeY() == 64) {
			floorLevel = 480;
		}
		boolean esta = (((underEffect.posY()) < floorLevel && !overEntity()));
		return esta;
	}

	private boolean overEntity() {
		ArrayList<MapObject> entities = underEffect.game().getObjects();
		GameEntity adjacent = null;
		for (int k = 0; k < entities.size(); k++) {
			adjacent = entities.get(k);
			Rectangle entidadProyectada = new Rectangle(underEffect.posX(),
			        underEffect.posY() + 16, underEffect.sizeX(),
			        underEffect.sizeY() + 1);
			if (entidadProyectada.intersects(adjacent.collisionRectangle())
			        && adjacent.posY() < 512) {
				return true;
			}
		}
		return false;
	}

}
